package com.dylan.历史.java8.StreamAPI;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.*;

/**
 * Created by Dylan on 2018/7/25.
 */
public class Stream处理6_原始流 {

    public static void main(String[] args) {
        /**
         * 创建原始流
         * 1. byte,short,int,char,boolean 使用 IntStream
         * 2. long 使用 LongStream
         * 3. float,double 使用 DoubleStream
         */
        IntStream stream1 = IntStream.of(1, 2, 3, 4);
        IntStream stream2 = IntStream.of('a', 'b', 'c', 'd');
        IntStream stream3 = Arrays.stream(new int[]{1, 2, 3, 4}, 1, 3);

        // range 和 iterator
        IntStream stream4 = IntStream.range(0, 10); // [0, 10)
        IntStream stream5 = IntStream.rangeClosed(0, 10); // [0, 10]
//        stream5.forEach(System.out::println);
        IntStream stream6 = IntStream.iterate(0, i -> i + 2).limit(10);
//        stream6.forEach(System.out::println);

        // 将对象流转换为原始流
        IntStream stream7 = getWords().mapToInt(String::length);
//        stream7.forEach(System.out::println);

        // 将原始流转换为对象流
        Stream<Integer> stream8 = IntStream.range(0, 10).boxed();

        // 原始流与对象流用法类似,如下是原始流与对象流的区别
        int[] arr1 = IntStream.range(0, 10).toArray();
        OptionalInt op1 = IntStream.range(0, 10).findFirst();
        int sum = IntStream.range(0, 10).sum();
        IntSummaryStatistics intSummaryStatistics = IntStream.range(0, 10).summaryStatistics();
        System.out.println(intSummaryStatistics.getAverage());

        // Random 可以生成随机的原始流
        IntStream stream9 = new Random().ints().limit(10);
        DoubleStream stream10 = new Random().doubles().limit(10);
        new Random().ints(0, 1000).limit(10).forEach(System.out::println);
    }

    private static Stream<String> getWords() {
        return Pattern.compile("[\\P{L}]+").splitAsStream("Ramesses VI was the fifth ruler of the Twentieth Dynasty of Egypt. He succeeded Ramesses V and reigned for about eight years in the mid-to-late 12th century BC before dying in his forties. Egypt lost control of its last strongholds in Canaan around the time of his reign. The pharaoh's power waned in Upper Egypt during his rule, while the high priest of Amun, Ramessesnakht, was turning Thebes in Upper Egypt into the religious capital and a second center of power on par with Pi-Ramesses in Lower Egypt, where the pharaoh resided. He was fond of cult statues of himself; more are known to portray him than any other Twentieth-Dynasty king after his father, Ramesses III. He usurped KV9, a tomb in the Valley of the Kings planned by and for Ramesses V, and had it enlarged and redecorated for himself. His mummy lay untouched for fewer than 20 years before pillagers damaged it.");
    }
}
